//
//  MainViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/4/1.
//

import UIKit
import  CoreData
class MainViewController: CommonViewController {
    fileprivate var scrollChange:(()->Void)?
    fileprivate var vcs:Array<MainTabviewController?> = []
    fileprivate var menuItems:Array<(String,Int)> = []
    fileprivate var currentIndex = 0
    fileprivate var beforeIndex = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.navigationController?.isNavigationBarHidden = true
        self.loadAdvert()
        let searchView = MainNavSearchView()
        view.addSubview(searchView)
        searchView.snp.makeConstraints({
            $0.top.equalTo(0)
            $0.height.equalTo(navigationBarHeight)
            $0.left.right.equalTo(0)
        })
        let userdefault = UserDefaults.standard
        userdefault.synchronize()
        // 顶部导航
        menuItems = [("关注",1),("推荐",2),("热榜",3),("抗疫",4),("视频",5),("北京",6),("国际",7),("关注",8),("推荐",9),("热榜",10),("抗疫",11),("视频",12),("北京",13),("国际",14)]
        let topView = TopMenusView(items: menuItems)
        self.view.addSubview(topView)
        topView.snp.makeConstraints({
            $0.left.right.equalTo(0)
            $0.height.equalTo(35)
            $0.top.equalTo(searchView.snp.bottom)
        })
        let pageController = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        
        topView.valueChanged = { [weak self]item in
            SystemLog(item)
            let index = self?.menuItems.firstIndex(where: { (arr) -> Bool in
               return arr.1 == item.1
            })
            guard index != self?.currentIndex else {
                return
            }
            self?.currentIndex = index!
            self?.updateViewControllers()
            let vc = self?.vcs[index!]
            pageController.setViewControllers([vc!], direction: .forward, animated: false) { (res) in
                SystemLog("setViewControllers|\(res)")
            }
            
        }
        
       
        self.scrollChange = {[weak self]in
            topView.nextTab(self!.currentIndex)
        }
        
        let group = DispatchGroup()
        let queue = DispatchQueue.global()
        queue.async(group: group) {
            sleep(10)
        }
        group.notify(queue: queue) {
            SystemLog("睡眠完成")
        }
        let oquqe = OperationQueue.main
        oquqe.maxConcurrentOperationCount = 10
        
        self.vcs = Array<MainTabviewController?>(repeating: nil, count: menuItems.count)
        self.updateViewControllers()
        
        pageController.dataSource = self
        pageController.delegate = self
        self.addChild(pageController)
        self.view.addSubview(pageController.view)
        pageController.view.snp.makeConstraints({
            $0.top.equalTo(topView.snp.bottom)
            if #available(iOS 11.0, *) {
                $0.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            } else {
                // Fallback on earlier versions
                $0.bottom.equalTo(0)
            }
            $0.left.equalTo(0)
            $0.width.equalTo(ScreenWidth)
        })
        pageController.setViewControllers([vcs[0]!], direction: .reverse, animated: false) { (res) in
            SystemLog("setViewControllers|\(res)")
        }
        NotificationMananger.addNotification(.Custom(name: "Loading\(navigationController!.description)"), target: self, selector: #selector(refersh))
        self.statusBarHidden = false
        
        SystemLog("viewDidLoad")
        var a1 = [1,2,3]
        
        var a2 = a1
        SystemLog(UnsafePointer(a2))
        a2[1] = 4
//        SystemLog(s)
        SystemLog(UnsafePointer(a2))
        SystemLog(a1)
        SystemLog(a2)
        let num = add(9) { (num) -> Int in
            num+1
        }
        
        
    }
    
    func add(_ num: Int,block:(Int)->Int) -> Int {
      return block(num)
    }

    
    func loadAdvert(){
        let vc = AdViewController()
        let nav = UINavigationController.init(rootViewController: vc)
        nav.modalPresentationStyle = .overCurrentContext
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationCapturesStatusBarAppearance = true
        self.tabBarController?.present(nav, animated: false, completion: {

        })
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    @objc func refersh(){
        SystemLog("开始刷新")
        self.perform(#selector(loaddone), with: self, afterDelay: 5)
    }
    @objc func loaddone()  {
        SystemLog("刷新结束")
        NotificationMananger.post(.Custom(name: "StopLoading\(self.navigationController!.description)"),object: self.navigationController?.tabBarItem.title)
    }
    func updateViewControllers() {
        for i in 0..<vcs.count {
            if i>self.currentIndex+1 || i<self.currentIndex-1 {
                vcs[i] = nil
            }else{
                if vcs[i] == nil {
                    let vc = MainTabviewController()
                    vc.reloadData(text: menuItems[i].0)
                    vcs[i] = vc
                }else{
                    vcs[i]?.reloadData(text: menuItems[i].0)
                }
            }
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        SystemLog("viewDidAppear")

    }
    override func viewDidDisappear(_ animated: Bool) {
        SystemLog("viewDidDisappear")

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        SystemLog("viewWillAppear")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        SystemLog("viewWillDisappear")

    }
}
extension MainViewController:UIPageViewControllerDelegate{
    func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return vcs.count
    }
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if finished && completed {
            // 滑动完成tabbars变动
            self.updateViewControllers()
            self.scrollChange!()
        }
    }
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        // 获取当前页码
        self.currentIndex = self.vcs.firstIndex(of: pendingViewControllers[0] as? MainTabviewController)!
    }
}
extension MainViewController:UIPageViewControllerDataSource{
    
    func nextViewController(_ viewController:UIViewController,isAfter:Bool) -> UIViewController? {
        guard var index = vcs.firstIndex(of: viewController as? MainTabviewController) else {
            return nil
        }
        if(isAfter){
            index += 1
        }else{
            index -= 1
        }
        
        if index < 0 || index == vcs.count{
            return nil
        }
        self.scrollChange!()
        SystemLog(index)
        return vcs[index]
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return nextViewController(viewController, isAfter: false)
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return nextViewController(viewController, isAfter: true)
    }

}
